<?php

namespace Cck\ArticlesSystem\Http\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * @property-read Role[]|Collection $roles
 * @property-read Permission[] $permissions
 */
class User extends Authenticatable implements JWTSubject
{
    use SoftDeletes;

    protected $table = 'users';

    protected $fillable = [
        'email', 'nickname', 'password', 'avatar'
    ];

    protected $hidden = [
        'password'
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function articles()
    {
        return $this->hasMany(Article::class, 'creator_id', 'id');
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles')->using(UserRole::class);
    }

    public function allKeywords()
    {
        return $this->hasMany(Keyword::class, 'user_id', 'id');
    }

    public function keywords()
    {
        return $this->allKeywords()->whereNull('used_at');
    }

    /**
     * 获得所有的权限（调用前请先with('roles.permissions')，不然会产生N+1问题）
     *
     * @return Collection|Permission[]
     */
    public function getPermissionsAttribute()
    {
        return $this->roles->map->permissions->flatten();
    }
}
